package niumao.minecraft.uhc.listener;

import niumao.minecraft.uhc.Main;
import niumao.minecraft.uhc.Util;
import org.bukkit.ChatColor;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable;

public class apprentice_sword implements Listener {

    private static final Main plugin = Main.getInstance();

    @EventHandler
    public void on(CraftItemEvent event) {
        ItemStack item = event.getCurrentItem();
        ItemMeta itemMeta = item.getItemMeta();
        Player player = (Player) event.getWhoClicked();
        if (itemMeta.getDisplayName().equalsIgnoreCase(Util.getStr("ApprenticeSword"))) {
            long minutes = 20 * 60;
            upgrade(player, 2, 3 * minutes);
            upgrade(player, 3, 5 * minutes);
            upgrade(player, 4, 10 * minutes);
        }
    }

    //武器升级
    private void upgrade(Player player, int level, long minutes) {
        new BukkitRunnable() {
            @Override
            public void run() {
                //获取某玩家的背包
                for (int i = 0; i <= 40; i++) {
                    //如果该背包的位置上没有物品，则继续
                    if (player.getInventory().getItem(i) == null) continue;
                    //更改物品属性
                    ItemStack item = player.getInventory().getItem(i);
                    assert item != null;
                    ItemMeta itemMeta = item.getItemMeta();
                    if (itemMeta == null) return;
                    if (itemMeta.getDisplayName().equalsIgnoreCase(Util.getStr("ApprenticeSword"))
                            && itemMeta.getEnchantLevel(Enchantment.DAMAGE_ALL) == level - 1) {
                        String[] str = {"一", "二", "三"};
                        itemMeta.addEnchant(Enchantment.DAMAGE_ALL, level, true);
                        item.setItemMeta(itemMeta);
                        player.sendMessage("你的武器" + itemMeta.getDisplayName() +
                                ChatColor.GOLD + "升级成功(" + str[level - 2] + "阶)");
                    }
                }
            }
        }.runTaskLater(plugin, minutes);
    }
}
